import java.awt.Point;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import org.rsbot.bot.Bot;
import org.rsbot.script.Calculations;
import org.rsbot.script.Script;
import org.rsbot.script.wrappers.RSInterface;
import org.rsbot.script.wrappers.RSInterfaceChild;
import org.rsbot.script.wrappers.RSItemTile;
import org.rsbot.script.wrappers.RSNPC;
import org.rsbot.script.wrappers.RSTile;

public class MFighter extends Script {

	long startTime;
	public boolean useFood = true;
	public boolean burybones = false;
	RSNPC npc;
	public int npcID;
	public int bury = random(4, 20);
	public int startExp[] = null;
	String[] names;
	int[] itemids = {};
	String[] itemnames = {};

	final int[] FoodID = { 1895, 1893, 1891, 4293, 2142, 291, 2140, 3228, 9980,
			7223, 6297, 6293, 6295, 6299, 7521, 9988, 7228, 2878, 7568, 2343,
			1861, 13433, 315, 325, 319, 3144, 347, 355, 333, 339, 351, 329,
			3381, 361, 10136, 5003, 379, 365, 373, 7946, 385, 397, 391, 3369,
			3371, 3373, 2309, 2325, 2333, 2327, 2331, 2323, 2335, 7178, 7180,
			7188, 7190, 7198, 7200, 7208, 7210, 7218, 7220, 2003, 2011, 2289,
			2291, 2293, 2295, 2297, 2299, 2301, 2303, 1891, 1893, 1895, 1897,
			1899, 1901, 7072, 7062, 7078, 7064, 7084, 7082, 7066, 7068, 1942,
			6701, 6703, 7054, 6705, 7056, 7060, 2130, 1985, 1993, 1989, 1978,
			5763, 5765, 1913, 5747, 1905, 5739, 1909, 5743, 1907, 1911, 5745,
			2955, 5749, 5751, 5753, 5755, 5757, 5759, 5761, 2084, 2034, 2048,
			2036, 2217, 2213, 2205, 2209, 2054, 2040, 2080, 2277, 2225, 2255,
			2221, 2253, 2219, 2281, 2227, 2223, 2191, 2233, 2092, 2032, 2074,
			2030, 2281, 2235, 2064, 2028, 2187, 2185, 2229, 6883, 1971, 4608,
			1883, 1885 };

	public boolean onStart(Map<String, String> s) {
		startTime = System.currentTimeMillis();

		itemnames = new String[itemids.length];
		for (int i = 0; i < itemids.length; i++) {
			itemnames[i] = IDtoName(itemids[i]);
			log(itemnames[i]);
		}
		startExp = new int[6];
		for (int i = 0; i < 6; i++) {
			startExp[i] = skills.getCurrentSkillExp(i);
		}
		return true;
	}

	public boolean needToEat() {
		int totHP = skills.getCurrentSkillLevel(STAT_HITPOINTS);
		int toEat = ((totHP / 100) * random(15, 20));
		if (getMyPlayer().getHPPercent() <= toEat) {
			return true;
		}
		return false;
	}

	public enum Action {
		FIGHTING, LOOTING, ANTIBAN, POTTING, PRAYER, WALKING_TO_MONSTER, EATING, ELIMINATE_SCRIPT
	}

	public Action getAction() {
		if (!isFullyLoggedIn()) {
			return Action.ANTIBAN;
		}
		
		if (inventoryContainsOneOf(FoodID)) {
			if (needToEat()) {
				return Action.EATING;
			}
		}

		return Action.ELIMINATE_SCRIPT;
	}

	private boolean isFullyLoggedIn() {
		if (!isLoggedIn()
				|| RSInterface.getInterface(378).getChild(45).getAbsoluteX() > 20
				&& !RSInterface.getInterface(149).isValid()) {
			return true;
		}
		return false;
	}

	@Override
	public int loop() {
		if (!isFullyLoggedIn()) {
			return random(2000, 3500);
		}

		if (getMyPlayer().getInteracting() == null) {
			RSItemTile tile;
			for (int i = 0; i < itemids.length; i++) {
				while ((tile = getGroundItemByID(itemids[i])) != null) {
					if (isInventoryFull()) {
						break;
					}
					if (!tileOnScreen(tile)) {
						break;
					}
					String action = "Take " + itemnames[i];
					clickTile(tile, action);
					waitTillMovingStart();
					while (getMyPlayer().isMoving())
						wait(random(20, 60));
				}
			}

			npc = getNearestFreeNPCToAttackByID(npcID);
			if (npc == null) {
				return random(400, 300);
			}
			if (clickNPC(npc, "Attack " + npc.getName())) {
				return random(100, 500);
			} else {
				return random(0, 100);
			}

		}
		return 0;
	}

	public boolean waitTillMovingStart() {
		long start = System.currentTimeMillis();
		while ((System.currentTimeMillis() - start) < 1500) {
			if (getMyPlayer().isMoving())
				return true;
		}
		return false;
	}

	public RSInterface getContinueInterface() {
		if (Bot.getClient().getRSInterfaceCache() == null) {
			return null;
		}
		final RSInterface[] valid = RSInterface.getAllInterfaces();
		for (final RSInterface iface : valid) {
			for (RSInterfaceChild c : iface.getChildren()) {
				if (c.getText().contains("Click here to continue")) {
					if (c.getAbsoluteX() < 3)
						return null;
				}
			}
			return iface;
		}
		return null;
	}

	public String IDtoName(int id) {
		try {
			URL url = new URL("http://itemdb-rs.runescape.com/viewitem.ws?obj="
					+ id);
			final BufferedReader reader = new BufferedReader(
					new InputStreamReader(url.openStream()));

			String line;
			int i = 0;
			while ((line = reader.readLine()) != null) {
				if (line.equals("<div class=" + '"' + "subsectionHeader" + '"'
						+ ">")) {
					i++;
					continue;
				}
				if (i == 1) {
					return line;
				}
			}
		} catch (Exception e) {

		}
		return null;
	}

	public String[] IDtoName(int[] ids) {
		ArrayList<String> s = new ArrayList<String>();
		for (int r = 0; r < ids.length; r++) {
			try {
				URL url = new URL(
						"http://itemdb-rs.runescape.com/viewitem.ws?obj="
								+ ids[r]);
				final BufferedReader reader = new BufferedReader(
						new InputStreamReader(url.openStream()));

				String line;
				int i = 0;
				while ((line = reader.readLine()) != null) {
					if (line.equals("<div class=" + '"' + "subsectionHeader"
							+ '"' + ">")) {
						i++;
						continue;
					}
					if (i == 1) {
						s.add(line);
						break;
					}
				}
			} catch (Exception e) {

			}
		}
		return s.toArray(new String[s.size()]);
	}

	// clickTile method by DDM
	public boolean clickTile(RSTile tile, String option) {
		Point p = Calculations.tileToScreen(tile);
		p.x += random(-5, 6);
		p.y += random(-5, 6);
		if (p.x < 0 || p.y < 0) {
			return false;
		}

		moveMouse(p);
		// wait(random(100,150));
		getMenuItems();
		@SuppressWarnings("unused")
		List<String> itemsList = getMenuItems();

		long waitTime = System.currentTimeMillis() + random(50, 250);
		boolean foundOption = false;
		while (System.currentTimeMillis() < waitTime && !foundOption) {
			wait(15);
			foundOption = (itemsList = getMenuItems()).get(0).toLowerCase()
					.contains(option.toLowerCase());
		}
		if (foundOption) {
			clickMouse(true);
			wait(random(150, 300));
			return true;
		}
		clickMouse(false);
		wait(random(150, 300));
		return atMenu(option);
	}

	// Clicks a NPC by Ruski
	private boolean clickNPC(final RSNPC npc, final String action) {
		try {
			int a;
			final StringBuffer npcCommandBuf = new StringBuffer();
			npcCommandBuf.append(action);
			npcCommandBuf.append(" ");
			npcCommandBuf.append(npc.getName());
			final String npcCommand = npcCommandBuf.toString();
			for (a = 10; a-- >= 0;) {
				if (npc.getInteracting() != null
						&& !npc.isInteractingWithLocalPlayer()) {
					return false;
				}
				final List<String> menuItems = getMenuItems();
				if (menuItems.size() > 1) {
					if (listContainsString(menuItems, npcCommand)) {
						if (menuItems.get(0).contains(npcCommand)) {
							clickMouse(true);
							return true;
						} else {
							// clickMouse(false);
							wait(random(230, 520));
							return atMenu(npcCommand);
						}
					}
				}
				final Point screenLoc = npc.getScreenLocation();
				if (!pointOnScreen(screenLoc)) {
					return false;
				}
				final Point randomP = new Point(random(screenLoc.x - 15,
						screenLoc.x + 15), random(screenLoc.y - 15,
						screenLoc.y + 15));
				if (randomP.x >= 0 && randomP.y >= 0) {
					moveMouse(randomP);
				}
			}
			return false;
		} catch (final Exception e) {
			log.log(Level.SEVERE, "clickNPC(RSNPC, String) error: ", e);
			return false;
		}
	}

	// Method for clicking an inventoryItem
	public boolean clickInventoryItem(int itemID, String option) {
		if (getCurrentTab() != TAB_INVENTORY) {
			openTab(TAB_INVENTORY);
		}
		int[] items = getInventoryArray();
		java.util.List<Integer> possible = new ArrayList<Integer>();
		for (int i = 0; i < items.length; i++) {
			if (items[i] == itemID) {
				possible.add(i);
			}
		}
		if (possible.size() == 0) {
			return false;
		}
		int idx = possible.get(random(0, possible.size()));
		Point t = getInventoryItemPoint(idx);
		moveMouse(t, 5, 5);
		long waitTime = System.currentTimeMillis() + random(50, 250);
		boolean found = false;
		while (!found && System.currentTimeMillis() < waitTime) {
			wait(15);
			if ((getMenuItems()).get(0).toLowerCase().contains(
					option.toLowerCase())) {
				found = true;
			}
		}
		if (found) {
			clickMouse(true);
			wait(random(150, 250));
			return true;
		}
		clickMouse(false);
		wait(random(150, 250));
		return atMenu(option);
	}

	// Walks onScreen Option
	public boolean WalkSmart(RSTile t2) {
		try {
			RSTile t = new RSTile(t2.getX() + random(-1, 1), t2.getY()
					+ random(-1, 1));
			Point p = tileToMinimap(t);
			if (tileOnScreen(t)) {
				if (clickTile(t, "Walk Here")) {
					while (getMyPlayer().isMoving()) {
						wait(random(200, 400));
					}
					return true;
				}
			} else {
				if (p.x == -1 || p.y == -1)
					return false;
				moveMouse(p, 2, 2);
				clickMouse(p, true);
				while (getMyPlayer().isMoving()) {
					wait(random(200, 400));
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

}
